﻿Imports System.Windows.Forms

Public Class FindDialog

    Public TheGrid As DataGridView
    Dim FirstFind As Boolean = True

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        FindIt()
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub FindDialog_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub FindIt()
        If Trim(FindBox.Text) = "" Then Exit Sub

        If TheGrid.Rows.Count = 0 Then Exit Sub

        Dim c, r As Integer
        Dim StartC, StartR As Integer

        If FirstFind Then
            StartC = 0
            StartR = 0
        Else
            StartC = TheGrid.CurrentCell.ColumnIndex
            StartR = TheGrid.CurrentCell.RowIndex + 1

            If StartR > TheGrid.Rows.Count - 1 Then
                StartC = StartC + 1
                StartR = 0

                If StartC > TheGrid.Columns.Count - 1 Then
                    StartC = 0
                End If
            End If
        End If

        For c = StartC To TheGrid.Columns.Count - 1
            For r = StartR To TheGrid.Rows.Count - 1

                If TheGrid.Item(c, r).Value.ToString.ToUpper.Contains(FindBox.Text.ToUpper) Then

                    If TheGrid.Item(c, r).Visible <> False Then
                        TheGrid.CurrentCell = TheGrid.Item(c, r)
                        FirstFind = False
                        Exit Sub
                    End If

                End If

            Next
        Next

        FirstFind = True
    End Sub

    Private Sub FindBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindBox.TextChanged
        FirstFind = True
    End Sub

   
    Private Sub FindDialog_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
        FindBox.Focus()
    End Sub
End Class
